from django.db.models import Sum
from django.db.models.functions import TruncMonth, ExtractMonth
from django.http import JsonResponse
from django.shortcuts import redirect,render

from firstplan import models
from firstplan.mine.pagination import Pagination
from firstplan.models import PlanEvent


def point(request):
    title="显示剩余积分"
    queryset1 = models.Person.objects.values("id")
    # print("queryset1: ",queryset1)
    queryset = models.EverydayResult.objects.annotate(month=TruncMonth('date')).values("person__person","person","month").annotate(point=Sum("event_id__deduct_point"))
    # print("queryset: ",queryset)
    if not queryset:
        queryset = queryset1
        # print("queryset-1",queryset)
        for item in queryset:
            item["point"] = 0
            item["sum_point"] = item["point"] + 2000
        return render(request,'point.html',{"title":title, "queryset":queryset})
    for item in queryset:
        # print(item)
        item["id"] = item["person"]
        item["sum_point"] = item["point"] + 2000
    return render(request,'point.html',{"title":title,"queryset":queryset})


def point_detail(request,person,month):
    """查询积分明细"""
    title = "查询积分明细"
    month = month[:-3]
    if person:
        queryset = models.EverydayResult.objects.filter(person=person,date__contains=month).order_by('-date','-id')
        print(queryset, type(queryset))
        page_obj = Pagination(request, queryset, page_param="page", page_size=9, plus=5)
        context = {
            "queryset": page_obj.queryset,  # 分完页后的数据
            "page_string": page_obj.html(),  # 生成页码
            'queryset': queryset,
            'title': title
        }
        return render(request,'everyday_list.html',context)
    return redirect('/point/')